// src/store/useTimeSlotStore.ts
import { create } from 'zustand';
import moment, { type Moment } from 'moment';

// 时间段类型定义（与组件内一致，抽离到全局）
export interface TimeSlot {
  id: string;
  date: Moment;
  isSelected: boolean;       // 当前用户选择状态
  isSelectedByOthers: boolean; // 他人选择状态
  isTemporary: boolean;      // 临时选择预览
  hour: number;
  minute: number;            // 0 或 30，代表半小时间隔
  isExpired: boolean;        // 是否已过期
}

// 选择范围类型
interface SelectedRange {
  start: Moment | null;
  end: Moment | null;
}

// 状态管理 Store 定义
interface TimeSlotStore {
  // 核心状态
  timeSlots: TimeSlot[];
  isSelecting: boolean;
  startSlotId: string | null;
  selectedRange: SelectedRange;
  initialized: boolean;

  // 原因填写相关状态
  showReasonModal: boolean; // 原因填写框显示状态
  reasonText: string;       // 用户输入的原因
  selectedReason: string | null; // 已保存的原因

  // 初始化与定时更新
  initializeTimeSlots: () => void;
  updateExpiredStatus: () => void;

  // 选择逻辑方法
  startSelection: (slotId: string) => { valid: boolean; slot?: TimeSlot };
  updateTemporarySelection: (slotId: string) => void;
  endSelection: (slotId: string) => { success: boolean; range?: SelectedRange };
  clearSelection: () => void;

  // 原因填写相关方法
  openReasonModal: () => void;
  closeReasonModal: () => void;
  updateReasonText: (text: string) => void;
  saveReason: () => boolean; // 保存原因（返回是否成功）
}

// 生成7天的时间段数据（抽离到 store 内）
const generateTimeSlots = (): TimeSlot[] => {
  const slots: TimeSlot[] = [];
  const now = moment();

  for (let day = 0; day < 7; day++) {
    for (let hour = 0; hour < 24; hour++) {
      for (let minute of [0, 30]) {
        const date = moment().add(day, 'days')
          .hour(hour).minute(minute)
          .second(0).millisecond(0);
        const isExpired = date.isBefore(now);
        // 模拟10%概率被他人选择（实际项目从接口获取）
        const isSelectedByOthers = !isExpired && Math.random() < 0.1;

        slots.push({
          id: `${date.format('YYYYMMDDHHmm')}`,
          date,
          isSelected: false,
          isSelectedByOthers,
          isTemporary: false,
          hour,
          minute,
          isExpired
        });
      }
    }
  }
  return slots;
};

// 创建 Zustand Store
export const useTimeSlotStore = create<TimeSlotStore>((set, get) => ({
  // 初始状态
  timeSlots: [],
  isSelecting: false,
  startSlotId: null,
  selectedRange: { start: null, end: null },
  initialized: false,

  // 原因填写初始状态
  showReasonModal: false,
  reasonText: '',
  selectedReason: null,

  // 初始化时间段数据
  initializeTimeSlots: () => {
    const slots = generateTimeSlots();
    set({ timeSlots: slots, initialized: true });
  },

  // 定时更新过期状态
  updateExpiredStatus: () => {
    const now = moment();
    set(state => ({
      timeSlots: state.timeSlots.map(slot => ({
        ...slot,
        isExpired: slot.date.isBefore(now)
      }))
    }));
  },

  // 开始选择（返回是否有效）
  startSelection: (slotId: string) => {
    const { timeSlots, isSelecting } = get();
    const slot = timeSlots.find(s => s.id === slotId);

    // 若已在选择中，直接返回（后续在组件内处理结束选择）
    if (isSelecting) return { valid: true, slot };
    // 若时间段无效（过期/被他人选择）
    if (!slot || slot.isExpired || slot.isSelectedByOthers) {
      return { valid: false };
    }

    // 重置之前的选择，标记当前为临时选择
    const updatedSlots = timeSlots.map(s => ({
      ...s,
      isSelected: false,
      isTemporary: s.id === slotId
    }));

    set({
      timeSlots: updatedSlots,
      isSelecting: true,
      startSlotId: slotId,
      selectedRange: { start: slot.date, end: null }
    });

    return { valid: true, slot };
  },

  // 更新临时选择预览（滑动时）
  updateTemporarySelection: (slotId: string) => {
    const { timeSlots, isSelecting, startSlotId } = get();
    if (!isSelecting || !startSlotId || startSlotId === slotId) return;

    const startIndex = timeSlots.findIndex(s => s.id === startSlotId);
    const currentIndex = timeSlots.findIndex(s => s.id === slotId);
    if (startIndex === -1 || currentIndex === -1) return;

    // 计算选择范围，过滤不可用时间段
    const start = Math.min(startIndex, currentIndex);
    const end = Math.max(startIndex, currentIndex);
    const hasUnavailable = timeSlots.slice(start, end + 1).some(
      s => s.isExpired || s.isSelectedByOthers
    );
    if (hasUnavailable) return;

    // 更新临时选择状态
    const updatedSlots = timeSlots.map((s, idx) => ({
      ...s,
      isTemporary: idx >= start && idx <= end && !s.isExpired && !s.isSelectedByOthers
    }));

    set({ timeSlots: updatedSlots });
  },

  // 结束选择（返回是否成功）
  endSelection: (slotId: string) => {
    const { timeSlots, startSlotId } = get();
    if (!startSlotId) return { success: false };

    const startIndex = timeSlots.findIndex(s => s.id === startSlotId);
    const endIndex = timeSlots.findIndex(s => s.id === slotId);
    if (startIndex === -1 || endIndex === -1) return { success: false };

    // 计算最终选择范围，验证可用性
    const start = Math.min(startIndex, endIndex);
    const end = Math.max(startIndex, endIndex);
    const hasUnavailable = timeSlots.slice(start, end + 1).some(
      s => s.isExpired || s.isSelectedByOthers
    );
    if (hasUnavailable) {
      // 清除临时选择，重置状态
      const updatedSlots = timeSlots.map(s => ({ ...s, isTemporary: false }));
      set({ timeSlots: updatedSlots, isSelecting: false, startSlotId: null });
      return { success: false };
    }

    // 标记最终选择状态
    const updatedSlots = timeSlots.map((s, idx) => ({
      ...s,
      isSelected: idx >= start && idx <= end && !s.isExpired && !s.isSelectedByOthers,
      isTemporary: false
    }));

    const selectedRange = {
      start: updatedSlots[start].date,
      end: updatedSlots[end].date
    };

    set({
      timeSlots: updatedSlots,
      isSelecting: false,
      startSlotId: null,
      selectedRange,
      reasonText: '' // 重置原因输入框
    });

    // 选择成功后，打开原因填写模态框
    get().openReasonModal();
    return { success: true, range: selectedRange };
  },

  // 清除所有选择
  clearSelection: () => {
    set(state => ({
      timeSlots: state.timeSlots.map(s => ({ ...s, isSelected: false, isTemporary: false })),
      selectedRange: { start: null, end: null },
      isSelecting: false,
      startSlotId: null,
      showReasonModal: false,
      reasonText: '',
      selectedReason: null
    }));
  },

  // 打开原因填写模态框
  openReasonModal: () => set({ showReasonModal: true }),

  // 关闭原因填写模态框
  closeReasonModal: () => set({ showReasonModal: false, reasonText: '' }),

  // 更新原因输入框内容
  updateReasonText: (text: string) => set({ reasonText: text }),

  // 保存原因（验证非空）
  saveReason: () => {
    const { reasonText, selectedRange } = get();
    if (!reasonText.trim()) return false; // 空原因不允许保存

    set({
      selectedReason: reasonText.trim(),
      showReasonModal: false
    });

    // 可在此处添加接口请求（如提交选择的时间段和原因到后端）
    console.log('提交选择结果：', {
      range: {
        start: selectedRange.start?.format('YYYY-MM-DD HH:mm'),
        end: selectedRange.end?.format('YYYY-MM-DD HH:mm')
      },
      reason: reasonText.trim()
    });

    return true;
  }
}));